package com.google.code.syncgear.plugin.fetch;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Namespace;
import org.dom4j.QName;
import org.dom4j.io.SAXReader;

import com.google.code.syncgear.core.exception.FetchException;
import com.google.code.syncgear.plugin.AbstractFetch;
import com.google.code.syncgear.plugin.bean.FetchResult;

public final class DeviantartFetch extends AbstractFetch {

	private static final long serialVersionUID = 3960770718281270424L;

	private static final String DEFAULT_CHARSET = "utf-8";

	@Override
	public List<FetchResult> fire(List<String> source) throws FetchException {
		List<FetchResult> results = new ArrayList<FetchResult>();
		SAXReader saxReader = new SAXReader();
		
		InputStream inputStream;
		try {
			inputStream = getInputStream(source.get(0));
			Document doc = saxReader.read(new InputStreamReader(inputStream, DeviantartFetch.DEFAULT_CHARSET));
			@SuppressWarnings("unchecked")
			List<Element> nodes = doc.selectNodes("/rss/channel/item");
			for (Element node : nodes) {
				FetchResult result = new FetchResult();
				String title = node.elementText("title");
				String link = null;
				String author = node.elementText("author");
				String image = 
					node.element(
							new QName(
									"content", 
									new Namespace("media", "http://search.yahoo.com/mrss/")
									)
							)
					.attributeValue("url");
				SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
						"EEE, dd MMM yyyy hh:mm:ss Z", Locale.US);
				Date pubDate = simpleDateFormat.parse(node.elementText("pubDate"));
				result.setTitle(title);
				result.setLink(link);
				result.setAuthor(author);
				result.setImage(image);
				result.setPubDate(pubDate);
				results.add(result);
			}
		} catch (MalformedURLException e) {
			throw new FetchException(e);
		} catch (IOException e) {
			throw new FetchException(e);
		} catch (DocumentException e) {
			throw new FetchException(e);
		} catch (ParseException e) {
			throw new FetchException(e);
		}		

		return results;
	}

}
